package edu.uic.ids517;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.myfaces.custom.fileupload.UploadedFile;

//import com.sun.org.glassfish.gmbal.ManagedObject;

@ManagedBean
@SessionScoped
public class ActionBeanFile {

	UploadedFile uploadedFile;
	String fileLabel;

	boolean fileImport;
	int numberRows;

	boolean fileImportError;
	MessageBean errorMessage;
	boolean renderParseTable;

	String fileName;
	long fileSize;
	String fileContentType;

	MessageBean message;
	ArrayList<DataBean> dataBean;
	DbaseBean dbase;

	public String getFileLabel() {
		return fileLabel;
	}

	public void setFileLabel(String fileLabel) {
		this.fileLabel = fileLabel;
	}

	public boolean isFileImport() {
		return fileImport;
	}

	public void setFileImport(boolean fileImport) {
		this.fileImport = fileImport;
	}

	public boolean isFileImportError() {
		return fileImportError;
	}

	public void setFileImportError(boolean fileImportError) {
		this.fileImportError = fileImportError;
	}

	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}


	public MessageBean getMessage() {
		return message;
	}

	public void setMessage(MessageBean message) {
		this.message = message;
	}

	public DbaseBean getDbase() {
		return dbase;
	}

	public void setDbase(DbaseBean dbase) {
		this.dbase = dbase;
	}

	public ArrayList<DataBean> getDataBean() {
		return dataBean;
	}

	public void setDataBean(ArrayList<DataBean> dataBean) {
		this.dataBean = dataBean;
	}

	public int getNumberRows() {
		return numberRows;
	}

	public void setNumberRows(int numberRows) {
		this.numberRows = numberRows;
	}

	public boolean isRenderParseTable() {
		return renderParseTable;
	}

	public String validateUser() {

		return null;

	}

	public String registerUser() {

		return null;

	}


	public String processFileUpload() {

		System.out.println("inside processFileUpload");

		String uploadedFileContents = null;
		message.setErrorMessage("");

		FacesContext context = FacesContext.getCurrentInstance();
		Map <String, Object> m = context.getExternalContext().getSessionMap();

		String path = context.getExternalContext().getRealPath("/WebContent/temp");
		System.out.println("path: " + path);

		File tempFile = null;
		FileOutputStream fos = null;

		int nCols = 0;
		int n = 0;

		fileImport = false;
		fileImportError = true;
		fileName = null;

		try {
			System.out.println("Inside 11111111111111111111111");

			fileName = uploadedFile.getName();
			fileSize = uploadedFile.getSize();
			fileContentType = uploadedFile.getContentType();

			System.out.println("fileName: " + fileName + "\n fileSize :" + fileSize + "\n fileContentType: " + fileContentType);

			// next line if want upload in String for memory processing
			// uploadedFileContents = new String(uploadedFile.getBytes());

			tempFile = new File(fileName);
			fos = new FileOutputStream(tempFile);

			// next line if want file uploaded to disk
			fos.write(uploadedFile.getBytes());

			// write file to temprory location

			File file = new File(path+"/newfile.txt");

			FileOutputStream fop = new FileOutputStream(file);

			// if file doesn't exists, then create it
			if (!file.exists()) {
				System.out.println("FILE Created");
				file.createNewFile();
			}

			// get the content in bytes
			fos.write(uploadedFile.getBytes());
			fop.flush();
			fop.close();

			Scanner s = new Scanner(tempFile);
			String input;
			Scanner d;

			input = s.nextLine();
			System.out.println("Inside input---"+input);
			String[] strArr=input.split(",");
			//System.out.println(input);

			nCols = strArr.length;
			dataBean = new ArrayList<DataBean>(nCols);
			// variables - header line
			for(int i=0; i<nCols; i++) {
				System.out.println("Inside 2222222222222222222222222222");
				dataBean.add(new DataBean());
				dataBean.get(i).setVariableName(strArr[i]);
				System.out.print(":" + strArr[i]);
			}


			while(s.hasNext()) {
				System.out.println("Inside 33333333333333333");
				input = s.nextLine();
				strArr=input.split(",");
				System.out.println(input);
				System.out.println("After printing input" + strArr);
				nCols = strArr.length;

				for(int i=0; i<nCols; i++) {
					System.out.print(":" + strArr[i]);
					if(n==0) {
						String type = "VARCHAR(45)";
						String dataType = "CATEGORICAL";

						try {
							Date dParse = Date.valueOf(strArr[i]);
							type = "DATE";
							dataType = "QUANTITATIVE";
						}
						catch (Exception e) {
							type = "VARCHAR(45)";
							dataType = "CATEGORICAL";
						}
						if(!type.equalsIgnoreCase("date"))
							try {
								Integer.parseInt(strArr[i]);
								type = "INTEGER";
								dataType = "COUNT";
							}
						catch (NumberFormatException e) {
							type = "VARCHAR(45)";
							dataType = "CATEGORICAL";
						}

						if((!type.equalsIgnoreCase("integer")) &&
								(!type.equalsIgnoreCase("date")))
							try {
								Double.parseDouble(strArr[i]); //NumberFormatExceptiontype = "DOUBLE";
								dataType = "QUANTITATIVE";
							}
						catch (NumberFormatException e) {
							type = "VARCHAR(45)";
							dataType = "CATEGORICAL";
						}

						dataBean.get(i).setDataType(type);
						dataBean.get(i).setDataValue(strArr[i]);
						dataBean.get(i).setVariableType(dataType);
					}
				}
				System.out.println(":");
				d = new Scanner(input);
				d.useDelimiter(",");
				n++;
			}
			s.close();
			numberRows = n;
			fileImport = true;

		} // end try
		catch (IOException e) {
			e.printStackTrace();
			message.setErrorMessage("Error reading data from file " + fileName + ", label: " + fileLabel);
			fileImportError = true;
		} // end catch

		numberRows = n;
		renderParseTable = true;
		return "SUCCESS";
	}

	public String processDataImport() {

		System.out.println("inside processFileUpload()");

		// Create table query
		StringBuffer sb = new StringBuffer("CREATE TABLE " + fileLabel + "(" );
		int nCols = (dataBean == null) ? 0 : dataBean.size();
		System.out.println("ncols: " + nCols);

		for(int i=0; i<nCols; i++) {
			System.out.println(
					dataBean.get(i).getVariableName() + "\t" +
							dataBean.get(i).getDataValue() + "\t" +
							dataBean.get(i).getDataType() + "\t" +
							dataBean.get(i).getVariableType() + "\t" );
			sb.append(dataBean.get(i).getVariableName() + " " +
					dataBean.get(i).getDataType());
			if(i != (nCols-1))
				sb.append(", ");
		}
		sb.append(", PRIMARY KEY (id) )");



		// Set query type
		dbase.setQueryType("CREATE");

		// Get Database Connection
		dbase.openConnection();

		// Execute the Create query
		dbase.executeSQL(sb.toString());

		/********************************** INSERT IN TO THE TABLE CREATED**************************************/

		// Create Insert Query
		System.out.println("INSERT START--------------------------------------");
		int nRows1 = dataBean.size();
		System.out.println("dataBean size is -----"+nRows1);

		for(int j =0; j<nRows1; j++)
		{
			StringBuffer sbInsert = new StringBuffer("INSERT into " + fileLabel + "(" );
			int nCols1 = (dataBean == null) ? 0 : dataBean.size();

			for(int i=0; i<nCols1; i++) {
				sbInsert.append(dataBean.get(i).getVariableName());
				if(i != (nCols1-1))
					sbInsert.append(", ");
			}
			sbInsert.append(") VALUES(");
			for(int i=0; i<nCols1; i++) {
				System.out.println("CHECK DATA TYPE"+dataBean.get(i).getDataType());
				if(dataBean.get(i).getDataType().equalsIgnoreCase("VARCHAR(45)")){
					sbInsert.append("'");
				}
				sbInsert.append(dataBean.get(i).getDataValue());
				if(dataBean.get(i).getDataType().equalsIgnoreCase("VARCHAR(45)")){
					sbInsert.append("'");
				}
				if(i != (nCols1-1))
					sbInsert.append(", ");
			}
			sbInsert.append(")");

			System.out.println("INSERT END--------------------------------------");
			System.out.println(sbInsert.toString());


			// Set query type
			dbase.setQueryType("INSERT");

			// Get Database Connection
			dbase.openConnection();

			// Execute the Create query
			dbase.executeSQL(sbInsert.toString());

		}

		return "SUCCESS";
	}

}
